/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/

KindEditor.plugin('insertfile', function(K) {
	var self = this, name = 'insertfile',
		allowFileUpload = K.undef(self.allowFileUpload, true),
		formatUploadUrl = K.undef(self.formatUploadUrl, true),
		uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
		extraParams = K.undef(self.extraFileUploadParams, {}),
		filePostName = K.undef(self.filePostName, 'nkFile');
	self.clickToolbar(name, function() {
		if (allowFileUpload) {
			var nkupload = K.nkupload({
				kEditor:self,
				fieldName : filePostName,
				url : K.addParam(uploadJson, 'fileType=file'),
				extraParams : extraParams,
				afterUpload : function(data) {
					if (data.code == "200") {
						var url = data.url;
						var fileName = data.fileName;
						if (formatUploadUrl) {
							url = K.formatUrl(url, 'absolute');
						}
						var html = '  <a class="ke-insertfile" href="' + url + '" data-ke-src="' + url + '" target="_blank">' + fileName + '</a>  ';
						self.insertHtml(html).hideDialog().focus();
						K.options.errorMsgHandler(self.lang('uploadSuccess'), "ok");
					} else {
						K.options.errorMsgHandler(data.message, "error");
					}
				},
				afterError : function(str) {
					K.options.errorMsgHandler(str, "error");
				}
			});
			nkupload.fileBox.change(function(e) {
				nkupload.submit();
			});
			nkupload.fileBox[0].click();
		}
	});
});
